import { mongo } from "../mogoConfig";

const cart = [
  { item: "sunblock", item_id: 5432, qty: 1, price: 5.19 },
  { item: "beach towel", item_id: 7865, qty: 2, price: 15.99 },
];
const payment = { customer: 98765, total: 37.17 };

const run = async () => {
  const session = mongo.startSession();
  try {
    session.startTransaction({
      readConcern: { level: "snapshot" },
      writeConcern: { w: "majority" },
      readPreference: "primary",
    });

    const orderTB = mongo.db("my_test").collection("orders");
    const inventoryTB = mongo.db("my_test").collection("inventory");
    const customerTB = mongo.db("my_test").collection("customers");

    const orderResult = await orderTB.insertOne(
      {
        customer: payment.customer,
        items: cart,
        total: payment.total,
      },
      { session }
    );

    for (const item of cart) {
      await inventoryTB.updateOne(
        {
          item: item.item,
        },
        {
          $inc: { qty: -item.qty },
        },
        { session }
      );
    }

    await customerTB.updateOne(
      {
        _id: payment.customer,
      },
      {
        // $set: { a: 1 }
        $push: { orders: orderResult.insertedId },
      },
      {
        session,
        upsert: true
      }
    );

    await session.commitTransaction();
    console.log("Transaction successfully committed.");
  } catch (error) {
    console.log(error);
    await session.abortTransaction();
  } finally {
    await session.endSession();
  }
};

run().finally(() => {
  mongo.close();
});
